#coding:utf-8
import socket
import os
import traceback
import struct
from threading import Thread


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "0.0.0.0"
port = 22
s.bind((host, port))
s.listen(5)

def send_file():
    pass

def start_f(client):
    path = r"D:\file\software\\"
    for root, dirs, names in os.walk(path):
        for name in names:
            _file = os.path.join(root, name)
            # 文件相对路径
            file_rela = _file.replace(path, "").encode("utf-8")
            # 文件大小，打包成8字节
            file_size = os.path.getsize(_file)
            file_size = struct.pack("q", file_size)
            # 文件头 15字节标识，8字节大小，105字节文件名
            head = b"FILE_NAME_LENTH" + file_size + struct.pack("233s", file_rela)
            client.sendall(head)
            with open(_file, "rb") as fp:
                while True:
                    f = fp.read(10485760)
                    if f:
                        client.sendall(f)
                    else:
                        break
            client.recv(2)
    client.sendall(b"FILE_SEND_00000")
    client.close()


def build(s):
    c, addr = s.accept()
    print("连接地址: %s" % str(addr))
    s = Thread(target = start_f, args = (c,))
    s.start()

while True:
    try:
        build(s)
    except:
        traceback.print_exc()